package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.MultiImageAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.bean.WorkLogBean;
import com.sx.zongzhi.presenter.AddOrUpdateWorkLogPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.AddOrUpdateWorkLog;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.AudioDialog;
import com.sx.zongzhi.widget.LoadDialog;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

public class AddWorkLogActivity extends BaseActivity implements AddOrUpdateWorkLog, UploadFileView {

    @BindView(R.id.et_Title)
    EditText et_Title;
    @BindView(R.id.et_Content)
    EditText et_Content;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    private int FILE_TYPE; // 10:文字、30：录音、50：视频、70：相册。
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    private AudioDialog audioDialog;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_work_log);
        setTitleName("工作日志新增");
        setTitleRight(R.string.submit);
        FILE_TYPE = getIntent().getIntExtra("FileType", 10);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        if (FILE_TYPE != 10) {
            rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
            adapter = new MultiImageAdapter(this, mAddPicClickListener);
            adapter.setList(selectList);
            rvImageRV.setAdapter(adapter);
            adapter.setOnItemClickListener(new MultiImageAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(final int position, View v) {
                    String type = selectList.get(position).getSuffixType();
                    String path= selectList.get(position).getPath();
                    if (".mp4".equalsIgnoreCase(type)) {
                        startActivity(new Intent(AddWorkLogActivity.this,
                                VideoPlayerActivity.class).putExtra(
                                "path",path));
                    } else if (".amr".equalsIgnoreCase(type)) {
                        if (audioDialog!=null){
                            audioDialog.startPlay(path);
                        }
                    }else if (".jpeg".equalsIgnoreCase(type)||".png".equalsIgnoreCase(type)||
                            ".jpg".equalsIgnoreCase(type)){
                        startActivity(new Intent(AddWorkLogActivity.this, ImagePlayActivity.class).putExtra(
                                "path", path));
                    }else {
                        ToastUtils.showToast(AddWorkLogActivity.this,"不能查看文件");
                    }
                }
            });
        } else {
            rvImageRV.setVisibility(View.GONE);
        }

        IDataStorage dataStorage = DataStorageFactory.getInstance(
                this, DataStorageFactory.TYPE_DATABASE);
        String userName = null;
        if (dataStorage.contains(UserBean.class, getPackageName())) {
            UserBean userBean = dataStorage.load(UserBean.class, getPackageName());
            if (userBean != null) {
                userName = userBean.getName();
            }
        }
        et_Title.setText(BaseUtil.TimeForData(System.currentTimeMillis()) + userName + "工作日志");
    }

    @OnClick({R.id.tv_right})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                commit();
                break;
        }
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                switch (FILE_TYPE) {
                    case 30:
                        if (audioDialog==null){
                            audioDialog=new AudioDialog(AddWorkLogActivity.this);
                            audioDialog.setCancelable(false);
                            audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                                @Override
                                public void getData(String filePath, int countdown) {
                                    PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                                    selectList.add(photoBean);
                                    if (adapter != null) adapter.notifyDataSetChanged();
                                }
                            });
                        }
                        audioDialog.show(audioDialog.AUDIO_RECODERD);
                        break;
                    case 50:
                        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                                .smallVideoWidth(640)
                                .smallVideoHeight(480)
                                .recordTimeMax(10 * 1000)
                                .maxFrameRate(20)
                                .minFrameRate(8)
                                .captureThumbnailsTime(1)
                                .videoBitrate(580000)
                                .build();
                        MediaRecorderActivity.goSmallVideoRecorder(AddWorkLogActivity.this, DisputeAddActivity.class.getName(), config);
                        break;
                    case 70:
                        PictureSelector.create(AddWorkLogActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.MULTIPLE)
                                .maxSelectNum(max)// 最大图片选择数量 int
//                                .previewImage(true)// 是否可预览图片
//                                .enableCrop(true)
                                .compress(true)
                                .compressGrade(Luban.CUSTOM_GEAR)
                                .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                }
            } else {
                ToastUtils.showToast(AddWorkLogActivity.this, "最多上传三项");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case MediaRecorderActivity.FOR_RESULT://拍视频
                    String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if (!TextUtils.isEmpty(videoUri)) {
                        String type = videoUri.substring(videoUri.lastIndexOf("."));
                        selectList.add(new PhotoBean(videoUri, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }


    private void commit() {
        String title = et_Title.getText().toString().trim();
        if (BaseUtil.isEmpty(title)){
            et_Title.setError( "请输入标题");
            return;
        }
        if ( title.length() > 25){
            et_Title.setError( "标题长度不可大于25");
            return;
        }
        if (FILE_TYPE == 10){
            String content = et_Content.getText().toString().trim();
            if (BaseUtil.isEmpty(content)){
                et_Content.setError( "请输入内容");
                return;
            }
            if ( content.length() > 1000){
                et_Content.setError( "内容长度不可大于1000");
                return;
            }
            LoadDialog.show(AddWorkLogActivity.this, "提交中...");
            new AddOrUpdateWorkLogPest(this).addWorkLog(this, title,
                    content, FILE_TYPE, null);
        }else {
            if (selectList.size() == 0){
                ToastUtils.showToast(AddWorkLogActivity.this, "请先添加附件");
                return;
            }
            List<File> files = new ArrayList<>();
            for (PhotoBean localMedia : selectList) {
                files.add(new File(localMedia.getPath()));
            }
            LoadDialog.show(AddWorkLogActivity.this, "提交中...");
            new UploadFilePest(this).uploadFile(this, files);
        }
    }

    @Override
    public void AddOrUpdateWorkLogSuccess(WorkLogBean result) {
        MyRxBus.get().post(new MsgEvent<>("WorkLogActivity",1,null));
        LoadDialog.dismiss(this);
        ToastUtils.showToast(AddWorkLogActivity.this, "添加成功");
        finish();
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(AddWorkLogActivity.this, message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        String content = et_Content.getText().toString().trim();
        if (content.length() > 1000){
            et_Content.setError( "内容长度不可大于1000");
            return;
        }
        new AddOrUpdateWorkLogPest(this).addWorkLog(this, et_Title.getText().toString().trim(),
                content, FILE_TYPE, beans);
    }
}
